﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Impl;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.PregnancyPregnancyTestCommand;
using MediatR;

namespace I_Produce.Read.API.Application.CommandHandlers.PregnancyPregnancyTestHandler
{
	public class PregnancyPregnancyTestQueryCommandHandler : IRequestHandler<PregnancyPregnancyTestQueryCommand, ApiResult<PagerResult<PregnancyPregnancyTest>>>
	{
		private readonly IPregnancyPregnancyTestRepository _repository;

		public PregnancyPregnancyTestQueryCommandHandler(IPregnancyPregnancyTestRepository repository)
		{
			_repository = repository;
		}

		public async Task<ApiResult<PagerResult<PregnancyPregnancyTest>>> Handle(PregnancyPregnancyTestQueryCommand request, CancellationToken cancellationToken)
		{
			var list = _repository.All().Result.Where(x => !x.IsDel);

			if (!string.IsNullOrEmpty(request.sPregnancyTestDate))
			{
				list = list.Where(x => x.PregnancyTestDate >= DateTime.Parse(request.sPregnancyTestDate));
			}

			if (!string.IsNullOrEmpty(request.ePregnancyTestDate))
			{
				list = list.Where(x => x.PregnancyTestDate < DateTime.Parse(request.ePregnancyTestDate).AddDays(1));
			}

			if (!string.IsNullOrEmpty(request.auricle))
			{
				list = list.Where(x => x.Auricle.Contains(request.auricle));
			}

			if (!string.IsNullOrEmpty(request.parityNumber))
			{
				list = list.Where(x => x.ParityNumber.Equals(request.parityNumber));
			}

			if (!string.IsNullOrEmpty(request.personCharge))
			{
				list = list.Where(x => x.PersonCharge.Contains(request.personCharge));
			}

			if (!string.IsNullOrEmpty(request.pregnancyTestResult))
			{
				list = list.Where(x => x.PregnancyTestResult.Contains(request.pregnancyTestResult));
			}

			var total = list.Count();
			var page = (int)Math.Ceiling(total * 1.0 / request.pageSize);

			list = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

			return new ApiResult<PagerResult<PregnancyPregnancyTest>>
			{
				Code = 200,
				msg = "成功",
				Data = new PagerResult<PregnancyPregnancyTest>
				{
					TotalCount = total,
					PageCount = page,
					Datas = list.ToList()
				}
			};
		}
	}
}
